﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ServiceModel;
using P2P_Social_networking;
using System.IO;
using System.Windows.Threading;
using System.Collections.Specialized;


namespace P2P_Social_networking
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 
    public partial class MainWindow : Window, PeerServer
    {
        Int32 currentProfile;
        Int32 highestProfile;
        StringCollection users;
        public void disconnect(Int32 profile, String username)
        {
            users.Remove(username + ":" + profile.ToString());
            App myContext = (App)App.Current;
            myContext.userList = users;
        }
        //Use for setting hop count
        //I have no means of testing this on my network, so someone should test this
        //[PeerHopCount]
        //Int32 maxhops;
        public void sendMessage(String message, Int32 userName, String sender)
        {
            //maxhops = 0;
            if (userName == currentProfile)
            {
                MessageBox.Show(message, "New message from " + sender);
            }
            else
            {
                

            }
        }
        public void getAllProfileIDs(Int32 profileID, String username)
        {
            
            if (profileID > highestProfile)
            {
                highestProfile = profileID;
                
            }
            if (users.Contains(username))
            {
               
            }
            else
            {
                if (username != Environment.UserName+":"+currentProfile)
                {
                    users.Add(username);
                    App myContext = (App)App.Current;
                    myContext.userList = users;
                }
                
            }
        }
        
        PeerClient myclient;
   
        DuplexChannelFactory<PeerClient> theclient;
        public MainWindow()
        {
            InitializeComponent();
            //TODO: Put in some code to check for application updates over P2P and download them.
            
            //TODO: Also remember to make a service-based subscription fee (to use this through a web-browser) – server virtualization (the client connects to the server and the server connects to the P2P network and charges a fee, but only for browser access
            InstanceContext frameworkmodel = new InstanceContext(this);
            theclient = new DuplexChannelFactory<PeerClient>(frameworkmodel,"PeerConfig");
            regProfileTimer = new DispatcherTimer();
            keyListener = new DispatcherTimer();
            connectService();
            sendWind = new msgSend(myclient);
            App myContext = (App)App.Current;
            users = new StringCollection();
            myContext.userList = new StringCollection();
            App.Current.Exit += new ExitEventHandler(Current_Exit);
            this.Closed += new EventHandler(MainWindow_Closed);
            
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
           
            App.Current.Shutdown();
        }

        void Current_Exit(object sender, ExitEventArgs e)
        {
            myclient.disconnect(currentProfile, Environment.UserName);
            myclient.Close();
        }
        DispatcherTimer keyListener;
        PersonalProfile myAccount;
        void broadcastOnline(Object sender, EventArgs e)
        {
            myclient.getAllProfileIDs(highestProfile, Environment.UserName+":"+currentProfile);
            msgBtn.Visibility = System.Windows.Visibility.Visible;
            
            myAccount = new PersonalProfile(Environment.UserName,"anonymous@no-reply.net",currentProfile);
            conStatus.Text = "You are logged in!";
        }
        void connectService()
        {
            conStatus.Text = "Contacting Cloud....";
            myclient = theclient.CreateChannel();
            myclient.Open();
            conStatus.Text = "Cloud opened.";
        }
        DispatcherTimer regProfileTimer;
        private void loginSuccess()
        {
        //Code to be executed upon successful login
        regProfileTimer.Tick+=new EventHandler(broadcastOnline);
        regProfileTimer.Interval = TimeSpan.FromSeconds(3);
        regProfileTimer.IsEnabled = true;
        App myapp = (App)App.Current;
        myapp.currentProfileID = currentProfile;
        conStatus.Text = "Connected as " + currentProfile.ToString();
        keyListener.Tick += new EventHandler(keyListener_Tick);
        keyListener.Interval = TimeSpan.FromMilliseconds(50);
        keyListener.Start();
        }
        msgSend sendWind;
        void keyListener_Tick(object sender, EventArgs e)
        {
            if (Keyboard.GetKeyStates(Key.LeftCtrl) == KeyStates.Down)
            {
                if (Keyboard.GetKeyStates(Key.LeftAlt) == KeyStates.Down)
                {
                    if (Keyboard.GetKeyStates(Key.M) == KeyStates.Down)
                    {
                        sendWind.Show();
                        sendWind.Activate();
                    }
                }
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //Connect the user to the service
            loginBtn.Visibility = System.Windows.Visibility.Collapsed;

            try
            {
                conStatus.Text = "Setting credentials....";
               String profileCode = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\IDWPID.txt");
               currentProfile = Convert.ToInt32(profileCode);
               loginSuccess();
            }
            catch (Exception)
            {
                //Check the network and see what profile IDs are available
                
                regProfileTimer.Interval = TimeSpan.FromSeconds(7);
                regProfileTimer.Tick += new EventHandler(regProfileTimer_Tick);
                regProfileTimer.Start();

            }
                
            
        }

        void regProfileTimer_Tick(object sender, EventArgs e)
        {
            regProfileTimer.Tick -= regProfileTimer_Tick;
            currentProfile = highestProfile+1;
            highestProfile = currentProfile;
            File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\IDWPID.txt",currentProfile.ToString());
            loginSuccess();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            sendWind.Show();
            sendWind.Activate();
        }
    }
}
